﻿namespace Pibby.Core.IO
{
	using System;
	using System.Collections.Generic;
	using System.Collections.ObjectModel;
	using System.Linq;

	public class IFileCollection : Collection<IFile>
	{
		public IFileCollection()
			: base()
		{
		}

		public IFileCollection(IList<IFile> files)
			: base(files)
		{
		}

		public long TotalSize
		{
			get
			{
				long totalSize = 0;

				foreach (var file in this.Items)
				{
					totalSize += file.Length;
				}

				return totalSize;
			}
		}

		public IFile Oldest
		{
			get
			{
				IFile oldestFile = null;

				DateTime earliestFileTime = DateTime.MaxValue;

				foreach (var file in this.Items)
				{
					if (file.LastWriteTime < earliestFileTime)
					{
						oldestFile = file;
						earliestFileTime = file.LastWriteTime;
					}
				}

				return oldestFile;
			}
		}

		public IFile Newest
		{
			get
			{
				IFile newestFile = null;

				DateTime latestFileTime = DateTime.MinValue;

				foreach (var file in this.Items)
				{
					if (file.LastWriteTime > latestFileTime)
					{
						newestFile = file;
						latestFileTime = file.LastWriteTime;
					}
				}

				return newestFile;
			}
		}

		public ReadOnlyCollection<string> Folders
		{
			get
			{
				var folders = new List<string>();

				foreach (var file in this.Items)
				{
					string folderName = file.FolderName.Split('\\').Last();

					if (!folders.Contains(folderName))
					{
						folders.Add(folderName);
					}
				}

				return new ReadOnlyCollection<string>(folders);
			}
		}

		public void SortBySize()
		{
			List<IFile> items = (List<IFile>)this.Items;

			items.Sort(delegate(IFile f1, IFile f2) 
			{ 
				long diff = f1.Length - f2.Length;

				if (diff > 0)
					return 1;
				
				if (diff < 0)
					return -1;

				return 0;
			});
		}

	}
}
